package com.ocom.xcxapi.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ocom.common.HttpUtils;
import com.ocom.common.constant.AliPayServiceUrl;
import com.ocom.common.entity.card.EntityXfMerchPayInfo;
import com.ocom.common.entity.card.EntityXfSignNo;
import com.ocom.common.entity.human.EntityPersonnelInfo;
import com.ocom.common.enums.ResultEnum;
import com.ocom.common.resp.Result;
import com.ocom.common.utils.ResultUtil;
import com.ocom.common.vo.PersonVo;
import com.ocom.common.vo.human.UserInfoVo;
import com.ocom.common.vo.human.XfUserInfoVo;
import com.ocom.security.authentication.YoCiUser;
import com.ocom.security.utils.SecurityUtils;
import com.ocom.xcxapi.client.CompanyClientService;
import com.ocom.xcxapi.client.HumanClientService;
import com.ocom.xcxapi.client.PayConfigClientService;
import com.ocom.xcxapi.vo.AlixcxFaceSignRequest;
import com.ocom.xcxapi.vo.AlixcxSignInfoResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@RestController
@PreAuthorize("hasRole('ROLE_ALIXCX')")
public class AliPayController {

    @Autowired
    private HumanClientService humanClientService;
    @Autowired
    private PayConfigClientService payConfigClientService;
    @Autowired
    private CompanyClientService companyClientService;

 //   private static final String PAY_URL = "http://192.168.11.249:8080/ocom_pay";
    private static final String PAY_URL = "http://192.168.3.123:32880/ocom_pay";//TODO 上线时需要更换为生产环境统一支付地址

    /**
     * 4.2 获取人员支付宝签约信息 (alixcx/signInfo)
     */
    @PostMapping(AliPayServiceUrl.URL_AlixcxSignInfo)
    public Result alixcxSignInfo() {
        log.info("=======================取人员支付宝签约信息========================");

        YoCiUser yoCiUser = SecurityUtils.getYoCiUser();
        Long comId = yoCiUser.getComId();
        Long pId = yoCiUser.getId();
        AlixcxSignInfoResponse response = new AlixcxSignInfoResponse();
        Result result = payConfigClientService.getUserSignInfo(comId, pId, 0, 28, -1);
        if (200 == result.getCode()) {
            EntityXfSignNo entityXfSignNo = JSON.parseObject(JSON.toJSONString(result.getData()), EntityXfSignNo.class);
            if (null != entityXfSignNo) {
                response.setFaceSign(1 == entityXfSignNo.getAlFace());
                response.setPaySign(1 == entityXfSignNo.getStatus());
            }
        }
        Result getUserInfoResult = humanClientService.getXfUserInfo(comId, pId);
        if (200 == getUserInfoResult.getCode()) {
            XfUserInfoVo xfUserInfoVo = JSON.parseObject(JSON.toJSONString(getUserInfoResult.getData()), XfUserInfoVo.class);
            response.setUserInfo(xfUserInfoVo);
        }
        return ResultUtil.success(response);
    }

    /**
     * 4.3支付宝人脸申请签约（alixcx/faceSign）
     */
    @PostMapping(AliPayServiceUrl.URL_AlixcxFaceSign)
    public Result alixcxFaceSign(@RequestBody AlixcxFaceSignRequest request) {
        log.info("=======================支付宝人脸申请签约========================");

        YoCiUser yoCiUser = SecurityUtils.getYoCiUser();
        String token = "";
        EntityXfMerchPayInfo entityXfMerchPayInfo = new EntityXfMerchPayInfo();
        entityXfMerchPayInfo.setComId(yoCiUser.getComId());
        entityXfMerchPayInfo.setMerchId(0);
        Result getPayInfoResult = payConfigClientService.getPayInfo(entityXfMerchPayInfo);
        if (200 == getPayInfoResult.getCode()) {
            EntityXfMerchPayInfo resultEntityXfMerchPayInfo = JSON.parseObject(JSON.toJSONString(getPayInfoResult.getData()), EntityXfMerchPayInfo.class);
            Map<String, Object> retMap = new HashMap<>();
            retMap.put("companyId", resultEntityXfMerchPayInfo.getCompanyId());
            retMap.put("userName", resultEntityXfMerchPayInfo.getUserName());
            retMap.put("password", resultEntityXfMerchPayInfo.getPassword());
            retMap.put("certNo", request.getIdCard());
            retMap.put("studentName", request.getPName());
            retMap.put("operatorUid", yoCiUser.getUsername());
            retMap.put("outUserId", String.format("%0" + 10 + "d", yoCiUser.getComId()) + yoCiUser.getDeptId());//10位单位号 (前面补0) + 手机号 (支付宝登录DeptId为手机号码)
            retMap.put("subCode", "SCHOOL_FACE_PASS_NAVIGATE");
            log.info("=======================支付宝人脸申请签约retMap========================:" + retMap);

            //向统一支付平台发起请求
            String json = HttpUtils.postsJson(PAY_URL + "/alischool/tokenCreate", retMap);
            log.info(json);
            JSONObject results = JSON.parseObject(json);
            log.info("=======================tokenCreate响应========================" + results);

            if (results.getInteger("code") == 200) {
                token = results.getString("data");
            } else {
                return ResultUtil.error(ResultEnum.Err_3055);
            }
            PersonVo personVo = new PersonVo();
            personVo.setComId(yoCiUser.getComId());
            personVo.setPId(yoCiUser.getId());
            personVo.setPName(request.getPName());
            personVo.setPPhone(yoCiUser.getDeptId());
            humanClientService.UpdatePerson(personVo);
        }

        return ResultUtil.success(token);
    }
    /**
     *
     * 4.6支付宝人脸解约（alixcx/delFaceSign）
     */
    @PostMapping(AliPayServiceUrl.URL_AlixcxDelFaceSign)
    public Result alixcxDelFaceSign() {
        YoCiUser yoCiUser = SecurityUtils.getYoCiUser();
        String token = "";

        UserInfoVo userInfoVo = new UserInfoVo();
        userInfoVo.setComId(yoCiUser.getComId());
        userInfoVo.setPId(yoCiUser.getId().intValue());
        userInfoVo.setOnlyOne(true);
        Result getPersonInfo = humanClientService.PersonnelGetPersonInfo(userInfoVo);

        if (200 == getPersonInfo.getCode()) {
            EntityPersonnelInfo entityPersonnelInfo = JSON.parseObject(JSON.toJSONString(getPersonInfo.getData()), EntityPersonnelInfo.class);

            EntityXfMerchPayInfo entityXfMerchPayInfo = new EntityXfMerchPayInfo();
            entityXfMerchPayInfo.setComId(userInfoVo.getComId());
            entityXfMerchPayInfo.setMerchId(0);
            Result getPayInfoResult = payConfigClientService.getPayInfo(entityXfMerchPayInfo);
            if (200 == getPayInfoResult.getCode()) {

                String uid = "";
                Result result = payConfigClientService.getUserSignInfo(userInfoVo.getComId(), userInfoVo.getPId().longValue(), 0, 28, -1);
                if (200 == result.getCode()) {
                    EntityXfSignNo entityXfSignNo = JSON.parseObject(JSON.toJSONString(result.getData()), EntityXfSignNo.class);
                    uid = entityXfSignNo.getFaceOpenId();
                }

                EntityXfMerchPayInfo resultEntityXfMerchPayInfo = JSON.parseObject(JSON.toJSONString(getPayInfoResult.getData()), EntityXfMerchPayInfo.class);
                Map<String, Object> retMap = new HashMap<>();
                retMap.put("companyId", resultEntityXfMerchPayInfo.getCompanyId());
                retMap.put("userName", resultEntityXfMerchPayInfo.getUserName());
                retMap.put("password", resultEntityXfMerchPayInfo.getPassword());

                retMap.put("certNo", entityPersonnelInfo.getPIdentity());
                retMap.put("userId", uid);

                retMap.put("subBizCode", "SCHOOL_PAYMENT_FACEPAY_BANK");
                retMap.put("bizCode", "SCHOOL_PAYMENT");
                //向统一支付平台发起请求
                String json = HttpUtils.postsJson(PAY_URL + "/alischool/kidsClose", retMap);

                JSONObject results = JSON.parseObject(json);
                if (results.getInteger("code") == 200) {
                    return ResultUtil.success();
                } else {
                    log.info("申请解约 【{}】",json);
                    return ResultUtil.error(ResultEnum.Err_3086);
                }
            }
            return ResultUtil.error(ResultEnum.Err_3048);
        }else{
            return ResultUtil.error(ResultEnum.Err_2036);
        }


    }

    /**
     * 4.4支付宝支付申请签约（alixcx/paySign）
     */
    @PostMapping(AliPayServiceUrl.URL_AlixcxPaySign)
    public Result alixcxPaySign() {
        log.info("=======================支付宝支付申请签约========================");
        YoCiUser yoCiUser = SecurityUtils.getYoCiUser();
        Map<String, Object> retMap = getSignMap(yoCiUser);
        retMap = getFaceOpenId(retMap, yoCiUser);
        log.info("=======================支付宝支付申请签约retMap========================:" + retMap);

        String token = "";
        if (null != retMap) {

            retMap.put("dk", 1);

            log.info("=======================统一支付平台发起请求 /alischool/facepayApply========================");
            //向统一支付平台发起请求
            String json = HttpUtils.postsJson(PAY_URL + "/alischool/facepayApply", retMap);
            log.info(json);
            JSONObject results = JSON.parseObject(json);
            log.info("=======================facepayApply响应========================" + results);
            if (results.getInteger("code") == 200) {
                token = results.getString("data");
            } else {
                return ResultUtil.error(ResultEnum.Err_3055);
            }
        } else {
            return ResultUtil.error(ResultEnum.Err_3051);
        }
        return ResultUtil.success(token);

    }

    /**
     * 4.5支付宝支付解约（alixcx/delPaySign）
     */
    @PostMapping(AliPayServiceUrl.URL_AlixcxDelPaySign)
    public Result alixcxDelPaySign() {
        log.info("=======================支付宝支付解约========================");

        YoCiUser yoCiUser = SecurityUtils.getYoCiUser();

        Map<String, Object> retMap = getSignMap(yoCiUser);
        retMap = getFaceOpenId(retMap, yoCiUser);
        log.info("=======================支付宝支付解约retMap========================:" + retMap);

        String token = "";
        if (null != retMap) {

            //向统一支付平台发起请求
            String json = HttpUtils.postsJson(PAY_URL + "/alischool/facepayClose", retMap);
            log.info(json);
            JSONObject results = JSON.parseObject(json);
            log.info("=======================facepayClose响应========================" + results);

            if (results.getInteger("code") == 200) {
                token = results.getString("data");
            } else {
                return ResultUtil.error(ResultEnum.Err_4119);
            }
        } else {
            return ResultUtil.error(ResultEnum.Err_4119);
        }

        return ResultUtil.success(token);
    }


    /**
     * 4.7签约返回同步返回的token查询(alixcx/tokenQuery)
     */
    @PostMapping(AliPayServiceUrl.URL_AlixcxTokenQuery)
    public Result alixcxTokenQuery() {
        log.info("=======================alixcxTokenQuery==========================");
        YoCiUser yoCiUser = SecurityUtils.getYoCiUser();
        String token = "";
        try {
            EntityXfMerchPayInfo entityXfMerchPayInfo = new EntityXfMerchPayInfo();
            entityXfMerchPayInfo.setComId(yoCiUser.getComId());
            entityXfMerchPayInfo.setMerchId(0);
            Result getPayInfoResult = payConfigClientService.getPayInfo(entityXfMerchPayInfo);
            if (200 == getPayInfoResult.getCode()) {
                EntityXfMerchPayInfo resultEntityXfMerchPayInfo = JSON.parseObject(JSON.toJSONString(getPayInfoResult.getData()), EntityXfMerchPayInfo.class);

                UserInfoVo userInfoVo = new UserInfoVo();
                userInfoVo.setComId(yoCiUser.getComId());
                userInfoVo.setPId(yoCiUser.getId().intValue());
                userInfoVo.setOnlyOne(true);
                Result getPersonInfo = humanClientService.PersonnelGetPersonInfo(userInfoVo);

                if (200 == getPersonInfo.getCode()) {
                    EntityPersonnelInfo entityPersonnelInfo = JSON.parseObject(JSON.toJSONString(getPersonInfo.getData()), EntityPersonnelInfo.class);
                    Map<String, Object> retMap = new HashMap<>();
                    retMap.put("companyId", resultEntityXfMerchPayInfo.getCompanyId());
                    retMap.put("userName", resultEntityXfMerchPayInfo.getUserName());
                    retMap.put("password", resultEntityXfMerchPayInfo.getPassword());
                    retMap.put("certNo", entityPersonnelInfo.getPIdentity());
                    retMap.put("studentName", entityPersonnelInfo.getPName());
                    retMap.put("operatorUserId", yoCiUser.getUsername());
                    retMap.put("outUserId", String.format("%0" + 10 + "d", yoCiUser.getComId()) + yoCiUser.getDeptId());//10位单位号 (前面补0) + 手机号 (支付宝登录DeptId为手机号码)
                    retMap.put("subCode", "SCHOOL_FACE_PASS_QUERY");
                    log.info("=======================alixcxTokenQueryretMap========================:" + retMap);

                    //向统一支付平台发起请求
                    String json = HttpUtils.postsJson(PAY_URL + "/alischool/tokenCreate", retMap);
                    log.info(json);
                    JSONObject results = JSON.parseObject(json);
                    log.info("=======================tokenCreate响应========================" + results);

                    if (results.getInteger("code") == 200) {
                        token = results.getString("data");

                        retMap = getSignMap(yoCiUser);
                        retMap.put("userToken", token);

                        if (null != retMap) {
                            //向统一支付平台发起请求
                            log.info("=======================tokenQuery==========================retMap参数：" + retMap);
                            json = HttpUtils.postsJson(PAY_URL + "/alischool/tokenQuery", retMap);
                            log.info(json);
                            results = JSON.parseObject(json);
                            log.info("=======================tokenQuery响应========================" + results);

                            if (results.getInteger("code") == 200) {
                                results = JSON.parseObject(results.getString("data"));
                                String schoolFacePassStatus = results.getString("schoolFacePassStatus");
                                String schoolFacePaymentStatus = results.getString("schoolFacePaymentStatus");
                                String userId = results.getString("userId");

                                signInfoHandle(yoCiUser.getComId(), yoCiUser.getId(), schoolFacePassStatus, schoolFacePaymentStatus, userId);

                                return ResultUtil.success(results);
                            }
//            else {
//                return ResultUtil.error(ResultEnum.Err_4118);
//            }
                        }
//        else {
//            return ResultUtil.error(ResultEnum.Err_4118);
//        }
                    } else {
//                    return ResultUtil.error(ResultEnum.Err_3055);
                    }
                }
            }


        } catch (Exception e) {
            e.printStackTrace();
        }

        return ResultUtil.success();
    }


    private Map getSignMap(YoCiUser yoCiUser) {
        Map<String, Object> retMap = new HashMap<>();

        EntityXfMerchPayInfo entityXfMerchPayInfo = new EntityXfMerchPayInfo();
        entityXfMerchPayInfo.setComId(yoCiUser.getComId());
        entityXfMerchPayInfo.setMerchId(0);
        Result getPayInfoResult = payConfigClientService.getPayInfo(entityXfMerchPayInfo);
        if (200 == getPayInfoResult.getCode()) {
            EntityXfMerchPayInfo resultEntityXfMerchPayInfo = JSON.parseObject(JSON.toJSONString(getPayInfoResult.getData()), EntityXfMerchPayInfo.class);
            retMap.put("companyId", resultEntityXfMerchPayInfo.getCompanyId());
            retMap.put("userName", resultEntityXfMerchPayInfo.getUserName());
            retMap.put("password", resultEntityXfMerchPayInfo.getPassword());
        }
        return retMap;
    }

    private Map getFaceOpenId(Map<String, Object> retMap, YoCiUser yoCiUser) {
        Result getUserSignInfoResult = payConfigClientService.getUserSignInfo(yoCiUser.getComId(), yoCiUser.getId(), 0, 28, -1);
        if (200 == getUserSignInfoResult.getCode()) {
            EntityXfSignNo entityXfSignNo = JSON.parseObject(JSON.toJSONString(getUserSignInfoResult.getData()), EntityXfSignNo.class);
            retMap.put("faceUid", entityXfSignNo.getFaceOpenId());
        }
        return retMap;
    }

    private Result signInfoHandle(Long comId, Long pId, String schoolFacePassStatus, String schoolFacePaymentStatus, String faceId) {
        final String CLOSE = "CLOSE";
        final String OPEN = "OPEN";

        Result getUserSignInfoResult = payConfigClientService.getUserSignInfo(comId, pId, 0, 28, -1);
        if (200 == getUserSignInfoResult.getCode()) {
            EntityXfSignNo entityXfSignNo = JSON.parseObject(JSON.toJSONString(getUserSignInfoResult.getData()), EntityXfSignNo.class);
            String statusStr = entityXfSignNo.getStatus()==0?"CLOSE":"OPEN";
            String faceStr = entityXfSignNo.getAlFace()==0?"CLOSE":"OPEN";
            //状态相同不做处理
            if(statusStr.equals(schoolFacePaymentStatus)
            && faceStr.equals(schoolFacePassStatus)){
                return ResultUtil.success();
            }
        }

        EntityXfSignNo entityXfSignNo = new EntityXfSignNo();
        entityXfSignNo.setComId(comId);
        entityXfSignNo.setPId(pId);
        entityXfSignNo.setMerchId(0);
        entityXfSignNo.setPayWay(28);
        payConfigClientService.delUserSign(entityXfSignNo);
        if (OPEN.equals(schoolFacePassStatus) || OPEN.equals(schoolFacePaymentStatus)) {
            if (OPEN.equals(schoolFacePaymentStatus)) {
                entityXfSignNo.setStatus(1);
            } else {
                entityXfSignNo.setStatus(0);
            }

            if (OPEN.equals(schoolFacePassStatus)) {
                entityXfSignNo.setAlFace(1);
            } else {
                entityXfSignNo.setAlFace(0);
            }

            entityXfSignNo.setFaceOpenId(faceId);
            payConfigClientService.addUserSign(entityXfSignNo);
        }
        return ResultUtil.success();
    }

    public static void main(String[] args) {
        String json = "{\"aa\":\"1\",\"bb\":2}";
        JSONObject results = JSON.parseObject(json);
        System.out.println(results);
    }


}